import { Fragment, useState } from 'react';
import { Input, Button, message, Form } from 'antd';
import { updatePwd } from '@/services/user';
import { connect } from 'dva';
import type { CurrentUser } from '@/pages/UserList/components/data';

const FormItem = Form.Item;

const SecurityView = (props) => {
  const { currentUser, dispatch } = props;
  const [helpMsg, setHelpMsg] = useState('');
  const [form] = Form.useForm();

  const okHandle = () => {
    form
      .validateFields()
      .then(async (fieldsValue) => {
        if (fieldsValue.password === fieldsValue.confirm) {
          setHelpMsg('');
          const res = await updatePwd({
            password: fieldsValue.password,
            id: currentUser.ID,
          });
          if (res.success) {
            message.success('密码已修改,请重新登陆');
            if (dispatch) {
              dispatch({
                type: 'login/logout',
              });
            }
          } else {
            message.success('修改失败,请重试');
          }
        } else {
          setHelpMsg('两次密码不一致,请重新输入~');
        }
      })
      .catch(() => {});
  };
  return (
    <Fragment>
      <Form layout="vertical" form={form}>
        <FormItem
          label="新密码"
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码(6~12位)',
              min: 6,
              max: 12,
            },
          ]}
        >
          <Input type="password" style={{ width: 200 }} />
        </FormItem>
        <FormItem
          label="再次输入新密码"
          name="confirm"
          help={helpMsg}
          rules={[
            {
              required: true,
              message: '请确认密码(6~12位)',
              min: 6,
              max: 12,
            },
          ]}
        >
          <Input type="password" style={{ width: 200 }} />
        </FormItem>
        <FormItem>
          <Button type="primary" onClick={okHandle}>
            更改密码
          </Button>
        </FormItem>
      </Form>
    </Fragment>
  );
};
export default connect(({ user }: { user: { currentUser: CurrentUser } }) => ({
  currentUser: user.currentUser,
}))(SecurityView);
